package org.mullin.stratego.server;

import org.mullin.stratego.client.LoginInfo;
import org.mullin.stratego.client.LoginService;
import org.mullin.stratego.shared.Match;
import org.mullin.stratego.shared.Player;

import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.ObjectifyService;

public class LoginServiceImpl extends RemoteServiceServlet implements LoginService{

	public static final long serialVersionUID = 1L;
	
	static {
		ObjectifyService.register(Player.class);
		ObjectifyService.register(Match.class);
	}
	
	@Override
	public LoginInfo login(String url) {
		System.out.println("loginServiceImpl- login(" + url + ").");
		
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		System.out.println(user);
		
		LoginInfo loginInfo = new LoginInfo();
		ChannelService channelService = ChannelServiceFactory.getChannelService();		
		
		if (null != user) {
			System.out.println("user = " + user);
			loginInfo.setLoggedIn(true);
			loginInfo.setEmailAddress(user.getEmail().trim());
			loginInfo.setNickname(user.getNickname());
			loginInfo.setLogoutUrl(userService.createLogoutURL(url));
			loginInfo.setToken(channelService.createChannel(user.getEmail()));
		} else {
			System.out.println("user was null.");
			String loginUrl = userService.createLoginURL(url);
			loginInfo.setLoggedIn(false);
			loginInfo.setLoginUrl(loginUrl);
		}
		return loginInfo;
	}

}
